import React, { Component } from 'react'
import FreeScrollBar from 'react-free-scrollbar'
import { connect } from 'react-redux'
import { cloneDeep } from 'lodash'
import * as I from '@ant-design/icons'
import { addWindow, addScrollEvent } from '@redux/actions'
import style from './Sider.module.less'
// import { companyName } from '@js/config'
import classNames from 'classnames'

class Sider extends Component {
  state = {
    menus: [],
    isReady: false,
    top: 0
  }

  // 是否展开菜单
  toggleFirstMenu (index) {
    const menus = this.state.menus.slice()
    const menu = menus[index]
    if (menu.children && menu.children.length > 0) {
      menu.showChildren = !menu.showChildren
      this.setState({
        menus
      })
    } else {
      this.openPage(menu)
    }
  }

  /**
   * 子菜单是否展示中
   */
  isChildrenSelected (list) {
    const goal = list.find(li => li.id === this.props.activeWindowId)
    return goal ? style.active : ''
  }

  /**
   * 从props中拷贝菜单
   */
  cloneMenus () {
    this.setState({
      menus: cloneDeep(this.props.menus)
    })
  }

  /**
   * 打开菜单
   */
  openPage ({ id = '', title = '', componentName = '', closable = true, meta = {}, isHome = false, openurl = '' }) {
    if (openurl) {
      window.open(openurl)
    } else {
      this.props.addWindow({ id, title, componentName, closable, meta, isHome })
    }
  }

  /**
   * 渲染菜单列表
   */
  renderMenuList () {
    return this.state.menus.map((menu, i) => {
      let Icon = null
      const blockClass = [style.menu__firstMenu]
      if (menu.icon) {
        Icon = I[menu.icon]
      } else {
        blockClass.push(style['no-icon'])
      }
      return (
        <li key={`${menu.id}-${i}`} className={this.isChildrenSelected(menu.children)}>
          <div className={blockClass.join(' ')}>
            <div onClick={() => this.toggleFirstMenu(i)}>
              {Icon ? <div className={style.menu__icon}><Icon /></div> : null}
              <span className={style.firstmenu__title}>{menu.title}</span>
              <div className={style.menu__direction}>
                {this.renderArrow(menu)}
              </div>
            </div>
            {this.renderSubMenu(menu)}
          </div>
        </li>
      )
    })
  }

  // 渲染箭头
  renderArrow (menu) {
    const Arrow = menu.showChildren ? I.UpOutlined : I.DownOutlined
    if (!menu.children.length) {
      return null
    }
    return (
      <Arrow className={style['menu__direction-icon']} />
    )
  }

  // 渲染子菜单
  renderSubMenu (menu) {
    if (menu.showChildren) {
      return (
        <ul className={style['sub-menu']}>
          {this.renderSubMenuList(menu)}
        </ul>
      )
    }
  }

  // 渲染子菜单列表
  renderSubMenuList (menu) {
    return menu.children.map((item, i) => {
      return (
        <li className={classNames({ [style.active]: item.id === this.props.activeWindowId })} key={`${item.id}-${i}`} onClick={() => this.openPage(item)}>{item.title}</li>
      )
    })
  }

  initDesktop () {
    const { windows, userInfo } = this.props
    const { id, desktop } = userInfo
    if (id && windows.length === 0) {
      this.openPage({ id: '0', title: '桌面', componentName: desktop || 'DefaultDesktop', closable: false, isHome: true })
    }
    // this.openPage({ id: 'ExpertManage', title: '专家库管理', componentName: 'ExpertManage', meta: { } })
    // this.openPage({ id: '123', title: '收案', componentName: 'AcceptCase', meta: { id: '1B393BC2ED8A17B37CC91DF4263639C8' } })
  }

  componentDidUpdate (prev) {
    // 当菜单为空时，根据store中的菜单初始化state中的菜单
    const { menus, userInfo, windows } = this.props
    if (prev.menus !== menus) {
      this.cloneMenus()
    }
    if (!prev.userInfo.id && userInfo.id && windows.length === 0) {
      this.initDesktop()
    }
  }

  componentDidMount () {
    this.initDesktop()
    // this.openPage({ id: '1123', title: '桌面', componentName: 'DepartmentDesktop', meta: { } }) // A6D38625CBF9955AE7110476297FFAB8
    this.setState({
      isReady: true
    })
  }

  // 渲染菜单滚动区域
  renderMenus () {
    if (this.state.isReady) {
      return (
        <FreeScrollBar className='mock'>
          <ul className={style.menu}>
            {this.renderMenuList()}
          </ul>
        </FreeScrollBar>
      )
    }
  }

  render () {
    return (
      <div className={style.sider}>
        <div className={style.sider__header}>
          {/* <img src={logo} /> */}
          {/* <h1>{companyName}</h1> */}
        </div>
        <div className={style.sider__content}>
          {this.renderMenus()}
        </div>
      </div>
    )
  }
}

function mapStateToProps (state) {
  return {
    userInfo: state.basic.userInfo,
    menus: state.pageMeta.menus,
    activeWindowId: state.pageMeta.activeWindowId,
    windows: state.pageMeta.windows
  }
}

function mapDispatchToProps (dispatch) {
  return {
    addWindow: (i) => dispatch(addWindow(i)),
    addScrollEvent: (i) => dispatch(addScrollEvent(i))
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(Sider)
